import { Service } from "egg";
import GeweChatSDK from "@/util/sdk/gewe_chat_sdk";

export default class GeweChatClientService extends Service {
  async getGeweChatSdk(tokenId?: string): Promise<GeweChatSDK> {
    const { app, ctx, config } = this;
    const { db } = ctx;
    const cache = app.geweChatSDKCache;

    if (tokenId) {
      const cacheSdk = cache.get(tokenId);

      if (cacheSdk) {
        return cacheSdk;
      }
    }

    let admin;

    if (tokenId) {
      admin = await db.admin.findUnique({
        where: {
          wxGeweToken: tokenId,
        },
        select: {
          wxGeweToken: true,
        },
      });
    }

    const {
      thirdPartyConfig: {
        cewechat: { url },
      },
    } = config;

    const geweChatSDK = new GeweChatSDK({ url, geweToken: tokenId });

    if (admin?.wxGeweToken) {
      cache.set(admin.wxGeweToken, geweChatSDK);
    }

    return geweChatSDK;
  }
}
